﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaixin.Components.Net;
using Kaixin.Components.Master.DTO;
using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Kaixin.Components.Master.DAL;

namespace Kaixin.Components.Master.BLL
{
    /// <summary>
    /// 大师机器人
    /// 创建：2009-12-11
    /// 版本：1.0
    /// 作者：吴鸣震
    /// </summary>
    class MasterRobot:Robot
    {
        public MasterRobot(string e, string p) : base(e, p) { }

        /// <summary>
        /// PK用户
        /// </summary>
        /// <param name="opponent">PK对象</param>
        /// <returns>PK结果</returns>
        public PKResult PK(Opponent opponent)
        {
            string url = @"http://www.kaixin001.com/!pker/!startpk.php?force=1&fuid={0}";
            
            HtmlDocument dc = AccessPage(string.Format(url, opponent.UID));
            JObject jo = JObject.Parse(dc.DocumentNode.InnerText);
            PKResult result = CanPK(jo);
            if (result == PKResult.General)
            {               
                int pkid = (int)jo["pkid"];                
                //jump http://www.kaixin001.com/!pker/!pk.php?pkid=39514224&fuid=3769117
                string selKFurl = @"http://www.kaixin001.com/!pker/!selkungfu.php?fuid={0}";
                string kfid="1";//默认1
                dc = AccessPage(string.Format(selKFurl, opponent.UID));
                foreach (var item in dc.DocumentNode.SelectNodes("//li/input"))
                {
                    if (item.Attributes.Contains("checked/"))
                    {
                        kfid = item.Attributes["value"].Value;
                        break;
                    }
                }
                string pkurl = @"http://www.kaixin001.com/!pker/!dopk.php?fuid={0}&pkid={1}&flag=0&kfid={2}";
                dc = AccessPage(string.Format(pkurl, opponent.UID, pkid, kfid));
                jo = JObject.Parse(dc.DocumentNode.InnerText);
                bool isWin = (bool)jo["base"]["result"]["win"];
#region json格式
                /*
                 "base": {
    "blood": {
      "11835338": "100",
      "1516532": "100"
    },
    "result": {
      "win": false,
      "helpself": false,
      "apprentice": false,
      "apprentice_reason": 0
    },
    "kungfu": {
      "1": "扫堂腿",
      "2": "杀鸡屠狗拳"
    }
  },
  "proc": [
    {
      "kid": 2,
      "dam": 5.6,
      "klb": 94.4,
      "fix": 0,
      "fkid": "2",
      "fdam": 5.6,
      "fklb": 94.4,
      "ffix": 0,
      "spec": 0,
      "against": false
    },{
      "kid": 2,
      "dam": 6.3,
      "klb": 88.7,
      "fix": 0,
      "fkid": "1",
      "fdam": 5.7,
      "fklb": 88.1,
      "ffix": 0,
      "spec": 0,
      "against": false
    }
  ],
  "start": {
    "result": {
      "pk": true,
      "validpkid": true,
      "validkf": true,
      "canpk": 0
    }
  }

                 */
#endregion

                result = isWin ? PKResult.Win : PKResult.Lose;
                if (result == PKResult.Win)
                {
                    UpdateLevel();
                }
            }
            return result;
            
        }

        public List<Opponent> GetMyOpponents()
        {
            string url = @"http://www.kaixin001.com/!pker/index.php";
            HtmlDocument doc = AccessPage(url);
            //js
            HtmlNode node = doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[1]/script[1]");
            int s = node.InnerText.IndexOf("[");
            int e = node.InnerText.IndexOf("]");

            string json = node.InnerText.Substring(s, e - s + 1);

            return GetByJSON(json);
        }

        public MyInfo GetMyInfo()
        {
            string url = @"http://www.kaixin001.com/!pker/index.php";
            HtmlDocument doc = AccessPage(url);
            MyInfo info = new MyInfo();
            info.Level = doc.DocumentNode.SelectSingleNode("id('r2_2')/div[2]/div[1]/div[4]/b[1]").InnerText;
            info.UPcount = doc.DocumentNode.SelectSingleNode("id('learntip')").InnerText;

            url = @"http://www.kaixin001.com/!pker/!kungfu.php";
            //TODO：获取监控账号的功夫
            //List<Kungfu> list = new List<Kungfu>();
            //doc = AccessPage(url);
            //foreach (var item in doc.DocumentNode.SelectNodes("//tr"))
            //{
                
            //}

            return info;
        }

        private List<Opponent> GetByJSON(string json) 
        {
            List<Opponent> list = new List<Opponent>();
            JArray ary = JArray.Parse(json);
            foreach (var item in ary)
            {
                JObject obj = (JObject)item;
                Opponent op = new Opponent();
                op.Name = (string)obj["real_name"];
                op.UID = (string)obj["uid"];
                op.Level = int.Parse((string)obj["level"]);
                op.IsDisciple = ((string)obj["icon"]).Contains("icon_disciple");
                op.IsTeacher = ((string)obj["icon"]).Contains("icon_teacher1");
                op.IsFull = ((string)obj["icon"]).Contains("icon_full");
                list.Add(op);
            }
            return list;
        }

        /// <summary>
        /// 升级
        /// </summary>
        private void UpdateLevel()
        {
            //TODO:升级
            MyInfo info = GetMyInfo();
            if (!info.UPcount.StartsWith("正在"))
            {
                HtmlDocument doc = AccessPage("http://www.kaixin001.com/!pker/!learn.php");
                HtmlNodeCollection nc = doc.DocumentNode.SelectNodes("//tr/td/label/input");
                string kid = string.Empty;
                foreach (var node in nc)
                {
                    if (node.Attributes.Contains("checked/"))
                    {
                        kid = node.Attributes["value"].Value;
                        break;
                    }
                }
                if (kid!=string.Empty)
                {
                    string submit_url = "http://www.kaixin001.com/!pker/!learn_submit.php?kid={0}&kungfu={0}";
                    AccessPage(string.Format(submit_url, kid));
                }
            }
        }
        /// <summary>
        /// 判断是否可以PK
        /// </summary>
        /// <returns></returns>
        private PKResult CanPK(JObject jo)
        {
            //result:{"f":0,"r":0,"pkid":39514224}
            //if round = 2 can'tPK everyday 3 times
            int round = (int)jo["r"];

            DateTime now = DateTime.Now;
            SettingXML xml = new SettingXML();
            Setting set = new Setting();
            set.Email = Email;
            xml.InitSetting(set);
            //PK限制时间未到
            if (now < set.NextPKTime)
                return PKResult.TheLackOfTime;
            if (jo["pkid"] != null)
                return  PKResult.General;
            else if (round < 2)
            {
                //每6小时内最多可以进行5场比武
                string t = jo["t"].ToString();

                int hour = int.Parse(t.Substring(1, 2));
                int minute = int.Parse(t.Substring(4, 2));
                DateTime nextTime = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);
                //记录下次比赛时间               
                set.NextPKTime = nextTime;

                xml.SetSetting(set);

                return PKResult.TheLackOfTime;
            }
            else
                return PKResult.MoreThanThreeTimes;

        }
    }
}
